<template>
  <div class="seart">
    <!-- 头部导航条 -->
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />

    <!-- 搜索 -->
    <van-search
      v-model="value"
      show-action
      shape="round"
      placeholder="请输入搜索关键词"
      @search="onSearch(value)"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch(value)">搜索</div>
      </template>
    </van-search>

    <!-- 推荐 -->
    <van-cell-group>
      <van-cell
        v-for="item in sugList"
        :key="item"
        icon="search"
        @click="onSearch(item)"
      >
        <span v-html="highLight(item, value)"></span>
      </van-cell>
    </van-cell-group>

    <!-- 历史记录 -->
    <van-cell-group>
      <van-cell title="历史记录"></van-cell>
      <van-cell
        @click="onSearch(item)"
        v-for="item in historyList"
        :key="item"
        :title="item"
      >
        <van-icon name="close" @click.stop="delHistory(item)" />
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggest } from '@/api/search'
import { setStorageHistory, getStorageHistory } from '@/utils/storage'

// import SearchResult from './results.vue'

export default {
  name: 'SearchView',
  // components: { SearchResult },
  data() {
    return {
      value: '',
      sugList: [], // 搜索关键词
      historyList: getStorageHistory() // 历史记录
    }
  },
  methods: {
    // 联想搜索关键词
    onInput() {
      // 防抖策略
      clearTimeout(this.timeId)
      this.timeId = setTimeout(async () => {
        if (!this.value) return // 如果搜索词为空，就不发送请求
        const res = await getSuggest(this.value)
        this.sugList = res.data.options
      }, 300)
    },
    // 搜索事件
    onSearch(item) {
      console.log('搜索中-')
      this.$router.push({
        path: '/search/result',
        query: {
          keyword: item
        }
      })
      // 点击搜索，添加将vlaue添加到历史记录中
      this.historyList = this.historyList.filter((obj) => obj !== item)
      this.historyList.unshift(item)
      setStorageHistory(this.historyList) // 存到本地
    },
    // 删除历史记录事件
    delHistory(item) {
      this.historyList = this.historyList.filter((obj) => obj !== item)
      setStorageHistory(this.historyList) // 存到本地
    },
    // 高亮效果方法
    highLight(str, str2) {
      const reg = new RegExp(str2, 'gi')
      return str.replace(reg, (item) => {
        return `<span style="color: red;">${item}</span>`
      })
    }
  }
}
</script>

<style></style>
